package cn.ym.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.ym.domain.Article;

import cn.ym.dto.ArticleDto;
import cn.ym.exception.BusinessException;
import cn.ym.mapper.ArticleMapper;
import cn.ym.mapper.UserMapper;
import cn.ym.query.ArticleQuery;
import cn.ym.service.ArticleService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;

import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 文章的业务层
 */
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired //只能用指定的API
    private MongoTemplate mgtemplate;
    @Autowired
    private UserMapper userMapper;
    @Override
    public void add(Article article) {
        //空值检验
        if(StrUtil.isEmptyIfStr(article.getArticleType())){
            throw new BusinessException("亲：文章类型不能为空");
        }
        if(StrUtil.isEmptyIfStr(article.getUserId())){
            throw new BusinessException("亲：文章作者不能为空");
        }
        if(StrUtil.isEmptyIfStr(article.getArticleName())){
            throw new BusinessException("亲：文章名称不能为空");
        }
        if(StrUtil.isEmptyIfStr(article.getArticleTag())){
            throw new BusinessException("亲：文章标签不能为空");
        }

        articleMapper.add(article);
        //保存到mongodb
//        mgtemplate.save(article);
    }

    @Override
    public void update(Article article) {
        //空值检验
        if(StrUtil.isEmptyIfStr(article.getArticleType())){
            throw new BusinessException("亲：文章类型不能为空");
        }
        if(StrUtil.isEmptyIfStr(article.getUserId())){
            throw new BusinessException("亲：文章作者不能为空");
        }
        if(StrUtil.isEmptyIfStr(article.getArticleName())){
            throw new BusinessException("亲：文章名称不能为空");
        }
        if(StrUtil.isEmptyIfStr(article.getArticleTag())){
            throw new BusinessException("亲：文章标签不能为空");
        }
        articleMapper.update(article);

        //通过数据库的id去查询mongodb里面的_id
//        Query query = new Query(Criteria.where("id").is(article.getId()));
//        Article mg = mgtemplate.findOne(query, Article.class);
//        if(mg==null){
//            mgtemplate.save(article);//然后再修改
//        }else {
//            //讲_id设置到新的article对象中
//            article.set_id(mg.get_id());
//            mgtemplate.save(article);//然后再修改
//        }


    }

    @Override
    public void delete(Long id) {

        articleMapper.delete(id);
        //通过前端传过来id删除mongodb里面的数据
//        Query query = new Query(Criteria.where("id").is(id));
//        mgtemplate.remove(query,Article.class);

    }

    /**
     * 批量删除
     * @param ids
     */
    @Override
    public void Patchdel(Long[] ids) {

        //删除mongodb
//        for (Long id : ids) {
//            //通过id值从mongodb中删除s
//            Query query = new Query(Criteria.where("id").is(id));
//            mgtemplate.remove(query,Article.class);
//            delete(id);
//        }
        articleMapper.Patchdel(ids);


    }

    @Override
    public List<ArticleDto> statisticsByArticleType() {

        return articleMapper.statisticsByArticleType();
    }
    /**
     *  按照文章发布时间分组统计数量
     */

    @Override
    public List<ArticleDto> selectArticleTimeStatistics() {
        return articleMapper.selectArticleTimeStatistics();
    }

    /**
     * 获取相关性文章列表数据
     * @param id
     * @return
     */
    @Override
    public List<Article> getDependentArticles(Long id) {

        return articleMapper.getDependentArticles( id);
    }

    /**
     * 根据文章类型获取所有文章列表信息
     * @param articleType
     * @return
     */
    @Override
    public List<Article> getArticleListByTypeId(Long articleType) {

        return articleMapper.getArticleListByTypeId(articleType);
    }


    @Override
    public Article findOne(Long id) {
        return articleMapper.findOne(id);
    }

    @Override
    public List<Article> findAll() {
        return articleMapper.findAll();
    }

    /**
     * 分页+高级查询
     * @param articleQuery
     * @return
     */
    @Override
    public List<Article> queryPage(ArticleQuery articleQuery) {
        //开启分页
        /**1.自动计算总数量
         * 2.根据驱动名计算 limit的第一个参数
         * 3.分页返回结果
         */
       PageHelper.startPage(articleQuery.getCurrentPage(), articleQuery.getPageSize());
       return articleMapper.queryPage(articleQuery);
    }

    /**
     * 根据页面对文章归档数据的遍历循环方式
     * @param time
     * @return
     */
    @Override
    public List<ArticleDto> getBlogGdList(String time) {
        time = "all".equalsIgnoreCase(time) ? "" : time;
        List<Article> list = articleMapper.getBlogGdList(time);

        //根据年份进行分组：百度看例子
        //String保存的是年份，List<Article>保存当前年份的集合
        Map<String, List<Article>> resultMap = list.stream().collect(Collectors.groupingBy(Article::getYear));

        List<ArticleDto> result = new ArrayList<>();
        //遍历resultMap，封装结果进行返回
        for(String year : resultMap.keySet()){
            ArticleDto dto = new ArticleDto();
            dto.setYear(year);
            dto.setArticleList(resultMap.get(year));
            result.add(dto);
        }
        return result;
    }
    /**
     *  获取文章点赞数数据
     */
    @Override
    public List<Article> getArticleStarNum() {
        return articleMapper.getArticleStarNum() ;
    }
    /**
     *  获取文章分类前5的数据
     */
    @Override
    public List<ArticleDto> getArticleType() {
        return articleMapper.getArticleType() ;
    }

}